package cbbx_sm.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Timestamp implements Comparable<Timestamp>{
	private static DateFormat formatter = 
			new SimpleDateFormat("yyyyMMddHHmmss");

	private long millisecondsValue;
	
	public Timestamp(long timeValue) {
		this.millisecondsValue = getMillisecondsValue(timeValue);
	}
	
	private Timestamp(long timeValue, boolean milliseconds) {
		millisecondsValue = timeValue;
	}
	

	public static Timestamp getNextTimeStamp(Timestamp currentTime){
		return getTimeStampInFuture(currentTime, 1);
	}
	
	public static Timestamp getTimeStampInFuture(Timestamp currentTime, long secondsToAdd) {
		return new Timestamp(currentTime.millisecondsValue + secondsToAdd * 1000, true);
	}
	
	public static Timestamp getTimeStampInPast(Timestamp currentTime, int secondsToSubtract) {
		return new Timestamp(currentTime.millisecondsValue - secondsToSubtract * 1000, true);
	}
	
	/**
	 * For example take 20090526111659 the next one should be
	 * 20090526111700
	 * @throws ParseException 
	 * */
	private static long getMillisecondsValue(long currentTime) {
		Date date;
		try {
			date = (Date)formatter.parse(String.valueOf(currentTime));
			return date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			System.exit(1);
			return -1;
		}
	}
	public static void main(String[] args){
		Timestamp time = new Timestamp(20090526111659l);
		System.out.printf("%d converted to %d%n", time, getNextTimeStamp(time));
		time = new Timestamp(20090526111658l);
		System.out.printf("%d converted to %d%n", time, getNextTimeStamp(time));
		time = new Timestamp(20090526235959l);
		System.out.printf("%d converted to %d%n", time, getNextTimeStamp(time));
		time = new Timestamp(20090526125959l);
		System.out.printf("%d converted to %d%n", time, getNextTimeStamp(time));
	}

	/**
	 * Computes the seconds between initial to final timestamp.
	 * @param finalTimestamp
	 * @param initialTimestamp
	 * @return
	 */
	public static long subtractTimestamps(Timestamp finalTimestamp,
			Timestamp initialTimestamp) {
		return (finalTimestamp.millisecondsValue - initialTimestamp.millisecondsValue) / 1000;
	}

	@Override
	public int compareTo(Timestamp timestamp) {
		return new Long(this.millisecondsValue).compareTo(timestamp.millisecondsValue);
	}

	@Override
	public String toString() {
		return formatter.format(new Date(this.millisecondsValue));
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ (int) (millisecondsValue ^ (millisecondsValue >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Timestamp other = (Timestamp) obj;
		if (millisecondsValue != other.millisecondsValue)
			return false;
		return true;
	}	
}